var MAP,infoWindow;

$(document).ready(function() {
    "use strict";

    window.onload = initSearchBoxHeight;
    window.onresize = initSearchBoxHeight;

    mapInit();
    loadData();
    showAreaList();
    _owl_carousel();
});

//改变搜索框的高度
function initSearchBoxHeight() {
    var width,height,offset1,offset2;
    width = window.innerWidth;
    height = window.innerHeight;
    offset1 = 100;
    offset2 = offset1 + 50;
    $("#left-panel").css("max-height", height - offset1 + "px");
    $(".list-tab-pane").css("max-height", height - offset2 + "px");
}

//初始化地图
function mapInit() {
    MAP = new AMap.Map('mapContainer', {
        center: [109.196513,27.728014],
        zoom: 12
    });
    //地图工具类
    MAP.plugin(['AMap.ToolBar','AMap.Scale'], function() {
        //工具条（缩放、平移、定位）
        MAP.addControl(new AMap.ToolBar({
            offset: new AMap.Pixel(20,30),
            position: "RB",
            locate: false
        }));
        //比例尺
        MAP.addControl(new AMap.Scale({
            offset: new AMap.Pixel(10,30)
        }));
    });
    //信息弹出窗
    infoWindow = new AMap.InfoWindow({
        offset: new AMap.Pixel(0, -30)
    });
    //地图事件
    mapListener();
}

//地图事件
function mapListener() {
    var el = $("#myTabContent");
    var icon = $("#switchBtn a");
    //地图拖动事件
    MAP.on("dragstart", function(e) {
        el.slideUp();
        icon.html('<i class="fa fa-angle-double-down"></i>');
    });
    //tab标签鼠标移入，显示列表
    $(".nav.nav-tabs").on("mouseover", function(e) {
        el.slideDown();
        icon.html('<i class="fa fa-angle-double-up"></i>');
    });
    //显示、隐藏按钮
    icon.on("click", function () {
        if(el.css("display") == "none") {
            icon.html('<i class="fa fa-angle-double-up"></i>');
        }else {
            icon.html('<i class="fa fa-angle-double-down"></i>');
        }
        el.slideToggle();
    });
}

//加载数据
function loadData() {
    var siteData = siteTestData;
    var collectData = collectTestData;

    var siteElem = $("#site-list");
    var collectElem = $("#collect-list");

    //页面绑定数据
    $.templates("#dataListTmpl").link("#site-list", siteData);
    $.templates("#collectListTmpl").link("#collect-list", collectData);


    //清除地图标注
    MAP.clearMap();
    //添加地图标注
    var siteGis = siteElem.gisMap({
        iconOffset: [0, 0],
        data:siteData
    });
    var collectGis = collectElem.gisMap({
        iconOffset: [0, -64],
        data:collectData
    });

    //显示和隐藏标注
    $("#siteLegend").on("click", function(e) {
        siteGis.markers.toggle();
        $(this).toggleClass("nagetive");
    });
    $("#collectLegend").on("click", function(e) {
        collectGis.markers.toggle();
        $(this).toggleClass("nagetive");
    });
}

//地区选择
function showAreaList() {
    var menu = $(".area-dropdown > .dropdown-menu");
    //地区选择按钮
    $(".area-dropdown").on("click", function (e){
        e.stopPropagation();
        menu.slideDown();

        $(document).one("click", function(e){
            menu.slideUp();
        });
    });
    //地区下拉菜单的一级列表
    $(".area-village > ul > li > a").on("mouseover", function (e) {
        e.stopPropagation();
        $(this).tab('show');
    });
    //地区下拉菜单的二级列表
    $("#siteAreaCountry").find("a").on("click",function (e) {
        e.stopPropagation();
        console.log($(this).attr("data-areaid"));
        $("#siteAreaLabel").text($(this).attr("title"));
        $("#siteAreaLabel").parent("a").attr("title",($(this).attr("title")));
        menu.slideUp();
    });
    $("#collectAreaCountry").find("a").on("click",function (e) {
        e.stopPropagation();
        console.log($(this).attr("data-areaid"));
        $("#collectAreaLabel").text($(this).attr("title"));
        $("#collectAreaLabel").parent("a").attr("title",($(this).attr("title")));
        menu.slideUp();
    });
}

//点击查看详情
function showDetail(id,type) {
    console.log(type + " " + id);
    $("#listTab").slideUp();
    $("#myTabContent.list-tab-pane").slideUp();
    if(type == 0) {
        $("#collectDetail").slideUp();
        $("#siteDetail").slideDown();
    }else if(type == 1) {
        $("#siteDetail").slideUp();
        $("#collectDetail").slideDown();
    }
}

//返回
function showTab() {
    $("#siteDetail").slideUp();
    $("#collectDetail").slideUp();
    $("#listTab").slideDown();
}

function switchMarker(t) {
    console.log(MAP.getLayers());
}

//添加地图标注
(function (){
    var Gis = {
        init : function (el, option) {
            var base = this;

            base.map = MAP;
            base.infoWindow = infoWindow;
            base.$elem = $(el);
            base.options = jQuery.extend({}, $.fn.gisMap.options, base.$elem.data(), option);

            base.addMarker();
        },
        addMarker : function (){
            var base = this;

            base.markers = [];

            for (var i = 0; i < base.options.data.length; i ++) {
                var marker = new AMap.Marker({
                    map: base.map,
                    position: [base.options.data[i].longitude, base.options.data[i].latitude],
                    animation: "AMAP_ANIMATION_DROP",
                    title: base.options.data[i].name,
                    offset: {x:-8,y:-34},
                    topWhenMouseOver: true,
                    icon: new AMap.Icon({
                        size: [25,32],
                        imageOffset: new AMap.Pixel(-25*i+base.options.iconOffset[0],0+base.options.iconOffset[1]),
                        image: base.options.icon
                    }),
                    extData: i
                });

                //鼠标移入、移出、点击标注与列表页效果
                marker.on("mouseover", function(e){
                    var t = e.target;
                    base.markerOver(t);
                }).on("mouseout", function(e){
                    var t = e.target;
                    base.markerOut(t);
                }).on("click", function(e) {
                    var t = e.target;
                    base.$elem.children("li").eq(t.getExtData()).trigger("click");
                });

                base.markers.push(marker);
            }

            //根据地图上添加的覆盖物分布情况，缩放平移地图到合适的视野级别
            base.map.setFitView();

            //列表鼠标移入移出标注效果
            base.onOverItem();

            //标注的显示、隐藏及切换
            base.markers.show = function() {
                for (var i = base.markers.length - 1; i >= 0; i--) {
                    base.markers[i].show();
                }
                base.map.setFitView();
            }
            base.markers.hide = function() {
                for (var i = base.markers.length - 1; i >= 0; i--) {
                    base.markers[i].hide();
                }
                base.map.setFitView();
            }
            base.markers.toggle = function() {
                if(base.markers.length > 0) {
                    if(base.markers[0].Af.visible) {
                        for (var i = base.markers.length - 1; i >= 0; i--) {
                            base.markers[i].hide();
                        }
                    }else {
                        for (var i = base.markers.length - 1; i >= 0; i--) {
                            base.markers[i].show();
                        }
                    }
                    base.map.setFitView();
                }
            }
        },
        onOverItem : function (){
            var base = this;

            var _el = base.$elem.children("li");
            _el.on("mouseover", function (e) {
                e.stopPropagation();
                var index = $(this).index();
                base.markerOver(base.markers[index]);
            });
            _el.on("mouseout", function (e) {
                e.stopPropagation();
                var index = $(this).index();
                base.markerOut(base.markers[index]);
            });
        },
        markerOver : function(t) {
            var base = this;

            var p = t.getExtData();
            t.setIcon(new AMap.Icon({
                size: [25,32],
                imageOffset: new AMap.Pixel(-25*p+base.options.iconOffset[0],-32+base.options.iconOffset[1]),
                image: base.options.icon
            }));
            base.$elem.children("li").eq(p).addClass("active");
            //打开信息窗口
            base.infoWindow.setContent(t.getTitle());
            base.infoWindow.open(base.map, t.getPosition());
        },
        markerOut: function(t) {
            var base = this;

            var p = t.getExtData();
            t.setIcon(new AMap.Icon({
                size: [25,32],
                imageOffset: new AMap.Pixel(-25*p+base.options.iconOffset[0],0+base.options.iconOffset[1]),
                image: base.options.icon
            }));
            base.$elem.children("li").eq(p).removeClass("active");
            //关闭信息窗口
            base.infoWindow.close();
        }
    };
    $.fn.gisMap = function (option) {
        var gis = Object.create(Gis);
        this.each(function() {
            gis.init(this, option);
        });
        return gis;
    };
    $.fn.gisMap.options = {
        icon: "images/markers_w300.png",
        iconOffset: [0,0]
    };
})(jQuery);

/** OWL Carousel
 **************************************************************** **/
function _owl_carousel() {
    var _container = jQuery(".owl-carousel");
    if(_container.length > 0) {

        _container.each(function() {

            var slider = jQuery(this);
            var options = slider.attr('data-plugin-options');

            // Progress Bar
            //var $opt = eval('(' + options + ')'); //convert text to json

            var defaults = {
                items:                  5,
                itemsCustom:            false,
                itemsDesktop:           [1199,4],
                itemsDesktopSmall:      [980,3],
                itemsTablet:            [768,2],
                itemsTabletSmall:       false,
                itemsMobile:            [479,2],
                singleItem:             false,
                itemsScaleUp:           false,

                slideSpeed:             200,
                paginationSpeed:        800,
                rewindSpeed:            1000,

                autoPlay:               false,
                stopOnHover:            false,

                navigation:             false,
                navigationText:         [
                    '<i class="fa fa-angle-left"></i>',
                    '<i class="fa fa-angle-right"></i>'
                ],
                rewindNav:              true,
                scrollPerPage:          false,

                pagination:             true,
                paginationNumbers:      false,

                responsive:             true,
                responsiveRefreshRate:  200,
                responsiveBaseWidth:    window,

                baseClass:              "owl-carousel",
                theme:                  "owl-theme",

                lazyLoad:               false,
                lazyFollow:             true,
                lazyEffect:             "fade",

                autoHeight:             false,
                autoplayHoverPause:     true,

                jsonPath:               false,
                jsonSuccess:            false,

                dragBeforeAnimFinish:   true,
                mouseDrag:              true,
                touchDrag:              true,

                transitionStyle:        false,

                addClassActive:         false,

                beforeUpdate:           false,
                afterUpdate:            false,
                beforeInit:             false,
                afterInit:              false,
                beforeMove:             false,
                afterMove:              false,
                afterAction:            false,
                startDragging:          false,
                afterLazyLoad:          false
            };

            var config = jQuery.extend({}, defaults, options, slider.data("plugin-options"));
            slider.owlCarousel(config);
        });
    }
}

//电商站点测试数据
var siteTestData = [{
    id: "3c98bc97-e022-487a-a2d0-06720daffdec",
    name: "金阳服务站点1",
    sitOwner: "王贵银1",
    latitude: 27.8962007,
    longitude: 109.878778,
    ownerPhone: "18285750197",
    address: "碧江区川硐镇龙塘坳村1组"
},{
    id: "3c98bc97-e022-487a-a2d0-06720daffded",
    name: "金阳服务站点2",
    sitOwner: "王贵银2",
    latitude: 27.8642007,
    longitude: 109.893553,
    ownerPhone: "18285750197",
    address: "碧江区川硐镇龙塘坳村2组"
},{
    id: "3c98bc97-e022-487a-a2d0-06720daffdee",
    name: "金阳服务站点3",
    sitOwner: "王贵银3",
    latitude: 27.866007,
    longitude: 109.879332,
    ownerPhone: "18285750197",
    address: "碧江区川硐镇龙塘坳村3组"
},{
    id: "3c98bc97-e022-487a-a2d0-06720daffdef",
    name: "金阳服务站点4",
    sitOwner: "王贵银4",
    latitude: 27.8752007,
    longitude: 109.873452,
    ownerPhone: "18285750197",
    address: "碧江区川硐镇龙塘坳村4组"
},{
    id: "3c98bc97-e022-487a-a2d0-06720daffdeg",
    name: "金阳服务站点5",
    sitOwner: "王贵银5",
    latitude: 27.8812007,
    longitude: 109.885623,
    ownerPhone: "18285750197",
    address: "碧江区川硐镇龙塘坳村5组"
},{
    id: "3c98bc97-e022-487a-a2d0-06720daffdeh",
    name: "金阳服务站点6",
    sitOwner: "王贵银6",
    latitude: 27.8582007,
    longitude: 109.877362,
    ownerPhone: "18285750197",
    address: "碧江区川硐镇龙塘坳村6组"
},{
    id: "3c98bc97-e022-487a-a2d0-06720daffdei",
    name: "金阳服务站点7",
    sitOwner: "王贵银7",
    latitude: 27.8792007,
    longitude: 109.864778,
    ownerPhone: "18285750197",
    address: "碧江区川硐镇龙塘坳村7组"
},{
    id: "3c98bc97-e022-487a-a2d0-06720daffdeg",
    name: "金阳服务站点8",
    sitOwner: "王贵银8",
    latitude: 27.7832007,
    longitude: 109.878788,
    ownerPhone: "18285750197",
    address: "碧江区川硐镇龙塘坳村8组"
},{
    id: "3c98bc97-e022-487a-a2d0-06720daffdek",
    name: "金阳服务站点9",
    sitOwner: "王贵银9",
    latitude: 27.8937007,
    longitude: 109.877777,
    ownerPhone: "18285750197",
    address: "碧江区川硐镇龙塘坳村9组"
},{
    id: "3c98bc97-e022-487a-a2d0-06720daffdel",
    name: "金阳服务站点10",
    sitOwner: "王贵银10",
    latitude: 27.8852222,
    longitude: 109.888888,
    ownerPhone: "18285750197",
    address: "碧江区川硐镇龙塘坳村10组"
}];
//集体经济测试数据
var collectTestData = [{
    id: "3c98bc97-e022-487a-a2d0-06720daffdem",
    name: "金阳食品合作社1",
    orgLiablePerson: "王贵银1",
    latitude: 27.8355532,
    longitude: 109.8311111,
    ownerPhone: "18285750197",
    address: "碧江区川硐镇龙塘坳村1组"
},{
    id: "3c98bc97-e022-487a-a2d0-06720daffden",
    name: "金阳食品合作社2",
    orgLiablePerson: "王贵银2",
    latitude: 27.8444444,
    longitude: 109.842232,
    ownerPhone: "18285750197",
    address: "碧江区川硐镇龙塘坳村2组"
},{
    id: "3c98bc97-e022-487a-a2d0-06720daffdeo",
    name: "金阳食品合作社3",
    orgLiablePerson: "王贵银3",
    latitude: 27.8333333,
    longitude: 109.8366666,
    ownerPhone: "18285750197",
    address: "碧江区川硐镇龙塘坳村3组"
},{
    id: "3c98bc97-e022-487a-a2d0-06720daffdep",
    name: "金阳食品合作社4",
    orgLiablePerson: "王贵银4",
    latitude: 27.8322222,
    longitude: 109.838888,
    ownerPhone: "18285750197",
    address: "碧江区川硐镇龙塘坳村4组"
},{
    id: "3c98bc97-e022-487a-a2d0-06720daffde1",
    name: "金阳食品合作社5",
    orgLiablePerson: "王贵银5",
    latitude: 27.832664,
    longitude: 109.837776,
    ownerPhone: "18285750197",
    address: "碧江区川硐镇龙塘坳村5组"
},{
    id: "3c98bc97-e022-487a-a2d0-06720daffder",
    name: "金阳食品合作社6",
    orgLiablePerson: "王贵银6",
    latitude: 27.847421,
    longitude: 109.841233,
    ownerPhone: "18285750197",
    address: "碧江区川硐镇龙塘坳村6组"
},{
    id: "3c98bc97-e022-487a-a2d0-06720daffdes",
    name: "金阳食品合作社7",
    orgLiablePerson: "王贵银7",
    latitude: 27.843133,
    longitude: 109.843212,
    ownerPhone: "18285750197",
    address: "碧江区川硐镇龙塘坳村7组"
},{
    id: "3c98bc97-e022-487a-a2d0-06720daffdet",
    name: "金阳食品合作社8",
    orgLiablePerson: "王贵银8",
    latitude: 27.836432,
    longitude: 109.836324,
    ownerPhone: "18285750197",
    address: "碧江区川硐镇龙塘坳村8组"
},{
    id: "3c98bc97-e022-487a-a2d0-06720daffdeu",
    name: "金阳食品合作社9",
    orgLiablePerson: "王贵银9",
    latitude: 27.836565,
    longitude: 109.834352,
    ownerPhone: "18285750197",
    address: "碧江区川硐镇龙塘坳村9组"
},{
    id: "3c98bc97-e022-487a-a2d0-06720daffdev",
    name: "金阳食品合作社10",
    orgLiablePerson: "王贵银10",
    latitude: 27.8563453,
    longitude: 109.823543,
    ownerPhone: "18285750197",
    address: "碧江区川硐镇龙塘坳村10组"
}];